<template>
  <div class="order-pay">
    <order-header title="订单支付">
      <template v-slot:tips>
        <span>
          温馨提示：请谨防钓鱼链接或诈骗电话，了解更多
        </span>
      </template>
    </order-header>
    <div class="wrapper">
      <div class="container">
        <div class="order-wrap">
          <div class="item-order">
            <div class="icon-succ"></div>
            <div class="order-info">
              <h2>订单提交成功！去付款咯～</h2>
              <p>请在<span>{{minute}}分{{second}}秒</span>内完成支付, 超时后将取消订单</p>
              <p>收货信息：{{`${receiver.receiverMobile} ${orderDetail.receiverName} ${receiver.receiverProvince} ${receiver.receiverCity} ${receiver.receiverDistrict} ${receiver.receiverAddress}`}}</p>
            </div>
            <div class="order-total">
              <p>应付总额：<span>{{totalPrice}}</span>元</p>
              <p>订单详情<em class="icon-down up" @click="showDetail=!showDetail" v-if="orderItemVoList.length"></em></p>
            </div>
          </div>
          <div class="item-detail" v-if="showDetail">
            <div class="item">
              <div class="detail-title">订单号：</div>
              <div class="detail-info theme-color">{{orderDetail.orderNo}}</div>
            </div>
            <div class="item">
              <div class="detail-title">收货信息：</div>
              <div class="detail-info">{{`${receiver.receiverMobile} ${orderDetail.receiverName} ${receiver.receiverProvince} ${receiver.receiverCity} ${receiver.receiverDistrict} ${receiver.receiverAddress}`}}</div>
            </div>
            <div class="item good">
              <div class="detail-title">商品名称：</div>
              <div class="detail-info">
                <ul>
                  <li v-for="(item,index) in orderItemVoList" :key="index">
                    <img v-lazy="item.productImage"/>{{item.productName}} {{item.currentUnitPrice}}元 x {{item.quantity}}个
                  </li>
                </ul>
              </div>
            </div>
            <div class="item">
              <div class="detail-title">发票信息：</div>
              <div class="detail-info">电子发票 个人</div>
            </div>
          </div>
        </div>
        <div class="item-pay">
          <h3>选择以下支付方式付款</h3>
          <div class="pay-way">
            <p>支付平台</p>
            <div class="pay pay-ali" :class="{'checked': checkedIndex===1}" @click="changeCheckedIndex(1)"></div>
            <div class="pay pay-wechat" :class="{'checked': checkedIndex===2}" @click="changeCheckedIndex(2)"></div>
          </div>
        </div>
      </div>
    </div>
    <scan-pay-code v-if="showPay" @close="closePayModel" :img="payImg"></scan-pay-code>
    <modal title="支付确认" btnType="3" :showModal="showPayModal" @cancel="showPayModal=false" sureText="查看订单" cancelText="未支付" @submit="goOrderList">
      <template v-slot:body>
        <div>
          是否已经完成支付？
        </div>
      </template>
    </modal>
  </div>
</template>

<script>
  import OrderHeader from '@/components/OrderHeader'
  import QRCode from 'qrcode'
  import ScanPayCode from '@/components/ScanPayCode';
  import Modal from '@/components/Modal'
  export default {
    name: 'order-pay',
    data() {
      return {
        showDetail: false,
        checkedIndex: 1,
        orderNo: this.$route.query.orderNo,
        orderDetail: {},
        orderItemVoList: {},
        totalPrice: 0,
        minutes: 30,
        seconds: 0,
        weixinContent: '',
        showPay: false,
        payImg: '',
        receiver: {},
        showPayModal: false,
        T: '' //定时器Id
      }
    },
    components: {
      ScanPayCode, Modal, OrderHeader
    },
    mounted() {
      this.getOrderDetail()
      this.timePasser()
    },
    methods: {
      changeCheckedIndex(val) {
        this.checkedIndex = val
        if(val === 1) {
          window.open('/#/order/alipay?orderId='+this.orderNo,'_blank')
        } else {
          this.axios.post('/pay',{
            orderId: this.orderNo,
            orderName: 'VueMI',
            amount: 0.01,
            payType: 2 // 微信
          })
          .then(res => {
            console.log(res)
            this.weixinContent = res.content
            QRCode.toDataURL(res.content)
            .then(url => {
              this.showPay = true
              this.payImg = url
              this.loopOrderState()
            })
            .catch(err => {
              console.error('微信二维码生成失败，请稍后再试'); 
            })
          })
          .catch(err => {
            console.error(err); 
          })
        }
      },
      getOrderDetail() {
        this.axios.get(`/orders/${this.orderNo}`)
        .then(res => {
          this.orderDetail = res
          this.orderItemVoList = res.orderItemVoList
          this.receiver = res.shippingVo
          this.orderItemVoList.forEach( item => {
            this.totalPrice += item.totalPrice
          })
        })
        .catch(err => {
          console.error(err); 
        })
      },
      addZero(n) {
        return n < 10? '0' + n : '' + n
      },
      timePasser() {
        let _this = this
        let time = window.setInterval(function() {
          if(_this.seconds === 0 && _this.minutes !== 0) {
            _this.seconds = 59
            _this.minutes -= 1
          } else if (_this.minutes === 0 && _this.seconds === 0) {
            _this.seconds = 0
            window.clearInterval(time)
          } else {
            _this.seconds -= 1
          }
        }, 1000)
      },
      closePayModel() {
        this.showPay = false
        this.showPayModal = true
        clearInterval(this.T)
      },
      goOrderList() {
        this.$router.push('/order/list')
      },
      // 轮询当前订单支付状态
      loopOrderState() {
        this.T = setInterval(() => {
          this.axios.get(`/orders/${this.orderNo}`)
          .then(res => {
            if(res.status === 20) {
              clearInterval(this.T)
              this.goOrderList()
            }
          })
          .catch(err => {
            console.error(err); 
          })
        }, 1000)
      }
    },
    watch: {
      second: {
        handler (newVal) {
          this.addZero(newVal)
        }
      },
      minute: {
        handler (newVal) {
          this.addZero(newVal)
        }
      }
    },
    computed: {
      second: function() {
        return this.addZero(this.seconds)
      },
      minute: function () {
        return this.addZero(this.minutes)
      }
    },
  }
</script>

<style lang='scss' scoped>
  .order-pay{
    .wrapper{
      background-color:#F5F5F5;
      padding-top:30px;
      padding-bottom:61px;
      .order-wrap{
        padding: 62px 50px;
        background-color: #fff;
        font-size:14px;
        margin-bottom:30px;
        .item-order{
          display: flex;
          align-items: center;
          .icon-succ{
            width: 90px;
            height: 90px;
            border-radius: 50%;
            background:url('/imgs/icon-gou.png') #80c58a no-repeat center;
            background-size:60px;
            margin-right:40px;
          }
          .order-info{
            margin-right: 248px;
            h2{
              font-size:24px;
              color:#333333;
              margin-bottom:20px;
            }
            p{
              color:#666666;
              span{
                color:#FF6700;
              }
            }
          }
          .order-total{
            &>p:first-child{
              margin-bottom:30px;
            }
            span{
              font-size:28px;
              color:#FF6700;
            }
            .icon-down{
              display:inline-block;
              width:14px;
              height:10px;
              background:url('/imgs/icon-down.png') no-repeat center;
              background-size:contain;
              margin-left:9px;
              transition:all .5s;
              cursor:pointer;
              &.up{
                transform: rotate(180deg);
              }
            }
            .icon-up{
              transform: rotate(180deg);
            }
          }
        }
        .item-detail{
          border-top: 1px solid #D7D7D7;
          padding-top: 47px;
          padding-left: 130px;
          font-size: 14px;
          margin-top: 45px;
          .item{
            margin-bottom:19px;
            .detail-title{
              float:left;
              width:100px;
            }
            .detail-info{
              display:inline-block;
              img{
                width: 30px;
                vertical-align: middle;
              }
            }
          }
        }
      }
      .item-pay{
        padding:26px 50px 72px;
        background-color:#ffffff;
        color: #333333;
        h3{
          font-size: 20px;
          font-weight: 200;
          color: #333333;
          padding-bottom: 24px;
          border-bottom: 1px solid #D7D7D7;
          margin-bottom: 26px;
        }
        .pay-way{
          font-size:18px;
          .pay{
            display:inline-block;
            width:188px;
            height:64px;
            border:1px solid #D7D7D7;
            cursor:pointer;
            &:last-child{
              margin-left:20px;
            }
            &.checked{
              border:1px solid #FF6700;
            }
          }
          .pay-ali{
            background:url('/imgs/pay/icon-ali.png') no-repeat center;
            background-size:103px 38px;
            margin-top:19px;
          }
          .pay-wechat{
            background:url('/imgs/pay/icon-wechat.png') no-repeat center;
            background-size:103px 38px;
          }
        }
      }
    }
  }
</style>
